<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/common/taglibs.jsp" %>
<%@ page import="com.starbaba.core.web.constant.WebConstants"%>
<%@ page import="com.starbaba.system.user.model.UserVO"%>
<!DOCTYPE html>
<html lang="en">
<head>
	<%@ include file="/common/common-css.jsp" %>
	<link rel="stylesheet" href="${ctx}/ace/css/just-tip.css"/>
 <script>
	  cmdList = "/apiActivityConf/queryList.action";
 </script>
 <style>
	#jquery-table td{cursor:pointer !important}
	.load_bg{background:#000;opacity:0.1;left:0px;top:0px;position:fixed;height:100%;width:100%;overflow:hidden;z-index:10000;}
	.load_img{left:50%;top:180px;position:fixed;height:50px;overflow:hidden;z-index:20000;}
 </style>
</head>
<body  class="no-skin">

<div  class="load_bg" style="display:none"></div>
<img src="http://img.xmiles.cn/commentloading.gif" class="load_img" style="display:none"/>
	<div class="page-content">
		<form id="queryForm" action="${cmdList}">
			<div class="page-content-area">
				<div class="row">
					 <div class="col-sm-12">
						<div class="widget-box" style="border:0px solid #ccc; border-top:none;border-bottom:none;margin-top:15px;">
						<hr style="margin-top:0px;margin-bottom:0x">
						<div class="widget-header widget-header-blue widget-header-flat">
								<h4 class="widget-title">API</h4>
								<div class="widget-toolbar">
									<a href="#" data-action="collapse">
										<i class="ace-icon fa fa-chevron-up"></i>
									</a>
								</div>	
							</div>
							<div class=" widget-body">
								<div class="widget-main" >
									<input type="hidden" name="userName" id="userName" value="<%=((UserVO) session.getAttribute(WebConstants.SESSION_ATTRIBUTE_USER)).getUsername() %>"/>
									<div class="form-group col-xs-12 col-sm-4 col-md-3 col-lg-3">
										<label class="col-sm-6 control-label" style="text-align:right" for="apiId">ID: </label>
										<div class="col-sm-6">
										    <input class="form-control" type="text" name="apiId" id="apiId"/>
										</div>
									</div>
									
									<div class="form-group col-xs-12 col-sm-4 col-md-3 col-lg-3">
										<label class="col-sm-6 control-label" style="text-align:right" for="apiName">配置模板名: </label>
										<div class="col-sm-6">
										    <input class="form-control" type="text" name="apiName" id="apiName"/>
										</div>
									</div>
									
									<div class="form-group col-xs-12 col-sm-4 col-md-3 col-lg-3">
										<label class="col-sm-6 control-label" style="text-align:right" for="thirdId">API的ID: </label>
										<div class="col-sm-6">
										    <input class="form-control" type="text" name="thirdId" id="thirdId"/>
										</div>
									</div>
								
									<div class="form-group col-xs-12 col-sm-4 col-md-3 col-lg-3">
										<label class="col-sm-6 control-label" style="text-align:right" for="thirdName">API名: </label>
										<div class="col-sm-6">
										    <input class="form-control" type="text" name="thirdName" id="thirdName"/>
										</div>
									</div>
									
								</div><!-- /.widget-main -->
						  </div><!-- /.widget-body -->
						</div><!-- /.widget-box -->
					</div><!-- /.col-sm-12 -->
					
					<div class="col-md-12 center">
						<div class="form-group col-xs-12 col-sm-4 col-md-3 col-lg-3" style="text-align:right">
							<button class="btn btn-purple  no-border" type="button" name="btn-query" onclick="query_any()">
									<i class="ace-icon fa fa-search icon-on-right bigger-110"></i>
										查询
							</button>
							&nbsp;&nbsp;&nbsp;
							<button class="btn btn-grey  no-border" onclick="Javascript:doAddItem();">
									<i class="ace-icon fa fa-undo icon-on-right bigger-110"></i>
										新增
							</button>
						</div>
					</div>						  
				</div><!-- /.row -->
				<hr style="display:none;" id="delete_hr">
					<div class="row">
						<div class="col-xs-12">
							<table id="jquery-table" class="table table-striped table-bordered table-hover">
							</table>
					</div><!-- /.col -->
				</div><!-- /.row -->
			</div><!-- /.page-content-area -->
		</form>
	    </div><!-- /.page-content -->
				
	  <%@ include file="/common/common-js.jsp" %>
	  <script type="text/javascript" src="${ctx}/js/call_func.js"></script>
	  <script src="${ctx}/ace/js/justTools.js"></script>
	  <script type="text/javascript">
		//【查询】按钮Click事件
		 function query_any(){
			$("#output").removeAttr("style");
			$(".load_bg").removeAttr("style");
			$(".load_img").removeAttr("style");
			if(jqTable != null){jqTable.fnDraw();}
			else{loaddata();}
			 $("#delete_btn").attr("style","display:block");
			 $("#delete_hr").attr("style","margin-top:0px;margin-bottom:20px;display:block");
		  }
 
		  var jqTable =null;
		  var loaddata = function(){
			jQuery(function($) {
					jqTable = $('#jquery-table').dataTable( {
	                    //数据列控制（包括对应返回JSON属性名称，对应表头列索引位置、数据转换封装等）
					    "columnDefs": [
					    	{	  
					    		  "title":"ID",
					    	  	  "targets": [0],
					    	  	  "data": "id",
					    	  	  "name": "id",   //JSON返回属性
					    	  	  "bSortable": false,
					    	},
					    	{
					    		  "title":"配置模板名",
					    		  "name":"api_name",
					    		  "data": "api_name",
					    	  	  "targets": [1], 
					    	  	  "bSortable": false
					    	},
					    	{
					    		  "title":"API的ID",
					    		  "name":"third_id",
					    		  "data": "third_id",
					    		  "defaultContent":"",
					    	  	  "targets": [2], 
					    	  	  "bSortable": false,
					    	  	  "render": function(value, type, row) {
					    	  		  if(value == "-1"){
					    	  			  return "非API";
					    	  		  } else {
					    	  			  return value;
					    	  		  }
					    	  	  }
					    	},
					    	{
					    		  "title":"API名称",
					    		  "name":"third_name",
					    		  "data": "third_name",
					    		  "defaultContent":"-",
					    	  	  "targets": [3], 
					    	  	  "bSortable": false,
					    	  	  "render": function(value, type, row) {
					    	  		  if(value == "" || value == null || value == undefined){
					    	  			  return "非API";
					    	  		  } else {
					    	  			  return value;
					    	  		  }
					    	  	  }
					    	},
					    	{
					    		  "title":"操作人",
					    		  "name":"user_name",
					    		  "data": "user_name",
					    	  	  "targets": [4], 
					    	  	  "bSortable": false
					    	},
					    	{
					    		  "title":"更新时间",
					    		  "name":"uptime",
					    		  "data": "uptime",
					    	  	  "targets": [5], 
					    	  	  "bSortable": false
					    	},
					    	{
					    	 	  "title":"操作",
					    	  	  "targets": [6] ,
					    	  	  "bSortable": false,
								  "render": function(value, type, row) { // 返回自定义内容
									   var text="";
								   		text="<a class='btn btn-success btn-sm' href='javascript:void(0)' onclick='editApi(" + row.id + ")'>编辑一级项</a>&nbsp;&nbsp;";
								   		text+="<a class='btn btn-success btn-sm' href='javascript:void(0)' onclick='copyApi(" + row.id + ")'>复制</a>&nbsp;&nbsp;";
								   		if(row.status == '1'){
								   			text+="<a class='btn btn-success btn-sm' href='javascript:void(0)' onclick='offline(" + row.id + ")'>下线</a>&nbsp;&nbsp;";
								   		}else{
								   			text+="<a class='btn btn-success btn-sm' href='javascript:void(0)' onclick='online(" + row.id + ")'>上线</a>&nbsp;&nbsp;";
								   		}
								   		text+="<a class='btn btn-success btn-sm' href='javascript:void(0)' onclick='deleteApi(" + row.id + ")'>删除</a>&nbsp;&nbsp;";
								   		return text;
						 		   },
					    	},
	                  	],
						"sAjaxSource": ctx + cmdList + "?rand=" + Math.random(),//数据源URL
						"fnServerData": function ( sSource, aoData, fnCallback ) {//从服务器请求数据
					   			var data = $('#queryForm').serializeObject();
								data.aoData = JSON.stringify(aoData);
								$.ajax({
									"dataType": 'json',
									"type": "POST",
									"url": sSource,
									"data":data,
									"success": function(resp){
										fnCallback(resp);
										initListPage();
										$(".load_bg").attr("style","display:none");
										$(".load_img").attr("style","display:none");
									},
									"error": function(XMLHttpRequest, textStatus, errorThrown) {
										$(".load_bg").attr("style","display:none");
										$(".load_img").attr("style","display:none");
										alert('请求服务器错误,请刷新重试！！');//错误提示，包括服务器重启导致的session失效
									},
								});
						},
						"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
							//console.log("---" + nRow + "+++++" + aData["id"]);
							//=====================这里实现行双击事件======================//
							nRow.ondblclick = function() {
							}; 
						},
						"sScrollXInner": "100%",
						"sScrollY": "100%",//如果不设置，IE会有问题
						 "aaSorting": [[0,"desc"]] //初始化加载，默认按第几列排序、排序方式（列从0开始计算）
				    });
					
					$('#jquery-table').delegate('select.backup-select','blur',function(){
						var _this = $(this);
						var itemId = _this.attr('item-id');
						var typeId = _this.val();
						var data = "itemId=" + itemId + "&typeId=" + typeId;
						$.ajax({
							"type": "POST",
							"dataType": 'json',
							"url": '${ctx}/apiModelBasisConf/updateType.action',
							"data": data,
							"timeout":300000,
							"success": function(data){
								backupTextJustToolsTip(_this,'修改成功','tooltip-suc');
							},
							"error": function(){
								backupTextJustToolsTip(_this,'修改失败','tooltip-fail');
							}
						});	
					});
					
					$('#jquery-table').delegate('input.backup-title','blur',function(){
						var _this = $(this);
						var itemId = _this.attr('item-id');
						var title = _this.val();
						var data = "itemId=" + itemId + "&title=" + title;
						$.ajax({
							"type": "POST",
							"dataType": 'json',
							"url": '${ctx}/apiModelBasisConf/updateTitle.action',
							"data": data,
							"timeout":300000,
							"success": function(data){
								backupTextJustToolsTip(_this,'修改成功','tooltip-suc');
							},
							"error": function(){
								backupTextJustToolsTip(_this,'修改失败','tooltip-fail');
							}
						});	
					});
					
					$('#jquery-table').delegate('input.backup-dataKey','blur',function(){
						var _this = $(this);
						var itemId = _this.attr('item-id');
						var dataKey = _this.val();
						var data = "itemId=" + itemId + "&dataKey=" + dataKey;
						$.ajax({
							"type": "POST",
							"dataType": 'json',
							"url": '${ctx}/apiModelBasisConf/updateDataKey.action',
							"data": data,
							"timeout":300000,
							"success": function(data){
								backupTextJustToolsTip(_this,'修改成功','tooltip-suc');
							},
							"error": function(){
								backupTextJustToolsTip(_this,'修改失败','tooltip-fail');
							}
						});	
					});
	
			});//end jquery初始化
		};
		
		function deleteApi(apiId){
			var answer = window.confirm("确定删除活动?");
			if(answer){
				var data = {"apiId":apiId};
				$.ajax({
					type:"post",	
					async:true,
					data:data,
					url: "${ctx}/apiActivityConf/deleteApi.action",
					success:function(data){
						var jsonObj = JSON.parse(data);
						var status = jsonObj.success;
						if(status == '1'){
							query_any();
						}else{
							alert("删除失败！");
						}
					},
					error:function(error){
						alert("删除失败！");
					}
				});
			
			}
		}
		
		//下线
		function offline(apiId){
			var answer = window.confirm("确定下线活动?");
			if(answer){
				var userName = $("#userName").val();
				var data = {"apiId":apiId,"status":"0","userName":userName};
				$.ajax({
					type:"post",	
					async:true,
					data:data,
					url: "${ctx}/apiActivityConf/updateStatus.action",
					success:function(data){
						var jsonObj = JSON.parse(data);
						var status = jsonObj.success;
						if(status == '1'){
							query_any();
						}else{
							alert("下线失败！");
						}
					},
					error:function(error){
						alert("下线失败！");
					}
				});
			}
		}
		
		//上线
		function online(apiId){
			var answer = window.confirm("确定上线活动?");
			if(answer){
				var userName = $("#userName").val();
				var data = {"apiId":apiId,"status":"1","userName":userName};
				$.ajax({
					type:"post",	
					async:true,
					data:data,
					url: "${ctx}/apiActivityConf/updateStatus.action",
					success:function(data){
						var jsonObj = JSON.parse(data);
						var status = jsonObj.success;
						if(status == '1'){
							query_any();
						}else{
							alert("上线失败！");
						}
					},
					error:function(error){
						alert("上线失败！");
					}
				});
			
			}
		}
		
		function copyApi(apiId){
			var answer = window.confirm("是否确认复制一份API模板？");
			if(answer){
				var username = $("#userName").val();
				var url = "/apiActivityConf/copyApi.action?apiId="+apiId+"&username="+username;
				url = encodeURI(url); 
				openDialogWithRand(url,1500,1000,"复制API",function (data){});
			}
		}
		
		function editApi(apiId){
			var url = "/apiActivityConf/editApi.action?apiId="+apiId;
			url = encodeURI(url); 
			openDialogWithRand(url,1500,1000,"编辑API",function (data){})
		}
		
		var typeList;
		function getTypeList(itemId,typeId){
			if(isBlock(typeList)){
				var url=ctx+"/apiModelBasisConf/typeList.action";
				$.ajax({
					"url":url,
					"type": "POST",
					"dataType": 'json',
					"async": false,
					"beforeSend": function(){
						
					},
					"success": function(data){
						typeList = data.members.typeList;
					},
					"error": function(){
						alert("操作失败");								 
					},
					"complete": function(){
					}
		        });
			}
			var html = "<select class='backup-select' item-id='"+itemId+"'>";
			var jsonObj = JSON.parse(typeList); 
			for(var i=0;i<jsonObj.length;i++){
				if(jsonObj[i].id == typeId){
					html+="<option value='"+jsonObj[i].id+"' selected='selected'>"+jsonObj[i].type_name+"</option>";
				}else{
					html+="<option value='"+jsonObj[i].id+"'>"+jsonObj[i].type_name+"</option>";
				}
			}
			html+="</select>";
			return html;
		}
		
		function doAddItem() {	
			var url = "/apiActivityConf/editApi.action";
			url = encodeURI(url); 
			openDialogWithRand(url,1500,1000,"新建API",function (data){});
		}
		
		jQuery(function(){
			query_any();
		});
		
		function deleteItem(itemId){
			var answer = window.confirm("是否确认删除?");
			if(answer){
				var data = {"itemId":itemId};
				$.ajax({
					type:"post",	
					async:true,
					data:data,
					url: "${ctx}/apiModelBasisConf/deleteItem.action",
					success:function(resp){
						query_any();
					},
					error:function(error){
						alert("删除失败！");
					}
				});
			
			}
		}
		
		function backupTextJustToolsTip(dom,content,theme){
			dom.justToolsTip({
				animation:"moveInLeft",
				contents:content,
				theme:theme,
				gravity:'left'
			});
			setTimeout(function(){
				$('.just-tooltip').remove();
			},3000); 
		}
		
		function isBlock(value){
			if(value==""||value==null||value==undefined){
				return true;
			}
			return false;
		}
	</script>
</body>
</html>
